package com.campuscrowdsourcing.server.controller;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campuscrowdsourcing.server.annotation.Log;
import com.campuscrowdsourcing.server.annotation.LoginCheck;
import com.campuscrowdsourcing.server.common.enums.Action;
import com.campuscrowdsourcing.server.domain.entity.Team;
import com.campuscrowdsourcing.server.domain.entity.TeamMember;
import com.campuscrowdsourcing.server.domain.model.AjaxResult;
import com.campuscrowdsourcing.server.mapper.TeamMapper;
import com.campuscrowdsourcing.server.mapper.TeamMemberMapper;
import com.campuscrowdsourcing.server.service.TeamMemberService;
import com.campuscrowdsourcing.server.service.TeamService;
import com.campuscrowdsourcing.server.utils.RequestUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 团队信息	提示：	money、score自动填充0 前端控制器
 * </p>
 *
 * @author Xinyuan Zhao
 * @since 2023-03-15
 */
@RestController
@RequestMapping("/api/team")
public class TeamController {
    @Resource
    private TeamService teamService;

    @PostMapping
    @Log(title = "新增团队", action = Action.INSERT)
    public AjaxResult saveTeam(@RequestBody Team team) {
        //TODO 成员信息
        teamService.save(team);
        return AjaxResult.success();
    }

    @PutMapping
    @Log(title = "编辑团队", action = Action.UPDATE)
    public AjaxResult updateTeam(@RequestBody Team team) {
        teamService.updateById(team);
        return AjaxResult.success();
    }

    @DeleteMapping("/{id}")
    @Transactional
    @Log(title = "删除团队", action = Action.DELETE)
    public AjaxResult deleteTeam(@PathVariable Integer id) {
        List<TeamMember> teamMembers = teamMemberService.list();
        for (TeamMember teamMember1 : teamMembers) {
            if(teamMember1.getTeamId().equals(id))
            {
                teamMemberService.removeById(teamMember1.getId());
            }
        }
        teamService.removeById(id);
        return AjaxResult.success();
    }

    @GetMapping
    @Log(title = "查看团队", action = Action.SELECT)
    public AjaxResult listTeam() {
        return AjaxResult.success(teamService.list());
    }

    @Resource
    private TeamMemberService teamMemberService;

    @GetMapping("/{id}")
    @Log(title = "id查询团队", action = Action.SELECT)
    public AjaxResult getTeamById(@PathVariable Integer id) {
        Team team = teamService.getById(id);
        if(team == null)
        {
            return AjaxResult.fail("该团队已删除或不存在");
        }
        return AjaxResult.success(team);
    }

    @Resource
    private TeamService TeamService;

    @GetMapping("/teamTaskMemberCount/{id}")
    @Log(title = "查看团队任务及成员的数量", action = Action.SELECT)
    public AjaxResult getTaskAndMemberCount(@PathVariable Integer id) {
        return AjaxResult.success(TeamService.findOnePlus(id));
    }

    @Resource
    private TeamMemberMapper teammemberMapper;
    @Resource
    private TeamMapper teamMapper;

    @GetMapping("/myManageTeam")
    @Log(title = "查看我管理的团队", action = Action.SELECT)
    @LoginCheck
    public AjaxResult listTeamByUserIdAndTeamRoleId() {
        QueryWrapper<TeamMember> queryWrapper = new QueryWrapper<>();
        Integer loginUserId = RequestUtil.getCurrentUserId();
        queryWrapper.eq("user_id", loginUserId)
                .le("teamRole_id", 2);

        List<TeamMember> teamMembers = teammemberMapper.selectList(queryWrapper);
//        for (Teammember teamMember : teamMembers) {
//            System.out.println("内容1："+teamMember.getTeamId());
//        }
        QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>();
        teamQueryWrapper.in("id", teamMembers.stream().map(TeamMember::getTeamId).toArray());
        List<Team> teams = teamMapper.selectList(teamQueryWrapper);
//        for (Team team : teams) {
//            System.out.println("内容2："+team.getName());
//        }
        return AjaxResult.success(teams);
    }

    @GetMapping("/myTeam")
    @Log(title = "查看我的团队", action = Action.SELECT)
    @LoginCheck
    public AjaxResult listTeamByUserId() {
        QueryWrapper<TeamMember> queryWrapper = new QueryWrapper<>();
        Integer loginUserId = RequestUtil.getCurrentUserId();
        queryWrapper.eq("user_id", loginUserId);

        List<TeamMember> teamMembers = teammemberMapper.selectList(queryWrapper);
//        for (Teammember teamMember : teamMembers) {
//            System.out.println("内容1："+teamMember.getTeamId());
//        }
        QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>();
        teamQueryWrapper.in("id", teamMembers.stream().map(TeamMember::getTeamId).toArray());
        List<Team> teams = teamMapper.selectList(teamQueryWrapper);
//        for (Team team : teams) {
//            System.out.println("内容2："+team.getName());
//        }
        return AjaxResult.success(teams);
    }

    @GetMapping("/page")
    @Log(title = "分页查询团队", action = Action.SELECT)
    public AjaxResult listTeamPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Team> queryWrapper = new QueryWrapper<Team>().orderByDesc("id");
        queryWrapper.like(!"".equals(name), "name", name);
        return AjaxResult.success(teamService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    @Log(title = "导出团队", action = Action.SELECT)
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Team> list = teamService.list();
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("Team信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }
}

